package com.xframe.xdal.core.util.redis.pool;

import com.xframe.xdal.config.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.commands.BasicCommands;
import redis.clients.jedis.commands.JedisCommands;
import redis.clients.jedis.commands.MultiKeyCommands;


@Slf4j
public class RedisJedisPool implements IRedisPool<Jedis> {

    private JedisPool pool;//sharded jedis连接池


    public void initPool(RedisConfig redisConfig) {

        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxTotal(redisConfig.getTotal());
        genericObjectPoolConfig.setMaxIdle(redisConfig.getMaxIdle());
        genericObjectPoolConfig.setMinIdle(redisConfig.getMinIdle());
        genericObjectPoolConfig.setTestOnBorrow(redisConfig.isTestBorrow());
        genericObjectPoolConfig.setTestOnReturn(redisConfig.isTestReturn());

        genericObjectPoolConfig.setBlockWhenExhausted(true);

        pool = new JedisPool(genericObjectPoolConfig,redisConfig.getHost(),redisConfig.getPort(),
                redisConfig.getTimeOut(),redisConfig.getPassword(),redisConfig.getDb());


    }


    public JedisCommands getClient() {
        return pool.getResource();
    }

    public Jedis getResource() {
        return pool.getResource();
    }

    @Override
    public BasicCommands getBasicCommands(){

        return pool.getResource();
    }

    @Override
    public MultiKeyCommands getMultiKeyCommands() {
        return pool.getResource();
    }

    @Override
    public void close(Jedis client) {
        try {
            if (client != null) {
                client.close();
            }
        } catch (Exception e) {
            log.error("return redis resource exception", e);
        }
    }
}
